<script lang="tsx">
import 'md-editor-v3/lib/style.css'
import { defineComponent, ref, unref } from 'vue'
import { MdEditor, config } from 'md-editor-v3'
import markdownItLinkAttributes from 'markdown-it-link-attributes'
import type { ExposeParam } from 'md-editor-v3'
import { allToolbars, mdHeadingId } from '../../config'

export default defineComponent({
  props: {
    modelValue: {
      type: String,
      required: true,
    },
  },
  emits: ['update:modelValue'],
  setup(props, ctx) {
    config({
      markdownItConfig(mdit) {
        // 新标签页打开链接
        mdit.use(markdownItLinkAttributes, {
          pattern: /^http/i,
          attrs: {
            target: '_blank',
            rel: 'noopener',
          },
        })
      },
    })

    const mdEditorRef = ref<ExposeParam>()
    const getMdEditorInstance = () => unref(mdEditorRef)
    ctx.expose({
      getMdEditorInstance,
    })

    return () => (
      <MdEditor
        ref={mdEditorRef}
        modelValue={props.modelValue}
        onUpdate:modelValue={value => ctx.emit('update:modelValue', value)}
        mdHeadingId={mdHeadingId}
        toolbars={allToolbars}
        {...ctx.attrs}
      >
        {{
          defToolbars: () => ctx.slots.defToolbars?.(),
          defFooters: () => ctx.slots.defFooters?.(),
        }}
      </MdEditor>
    )
  },
})
</script>

<style lang="less">
/* 目录样式 */
.md-editor-catalog.md-editor-catalog-editor {
  .md-editor-catalog-link {
    line-height: 18px;
  }

  .md-editor-catalog-link span {
    color: inherit;
  }

  .md-editor-catalog-link span:hover {
    color: var(--el-color-primary);
  }

  .md-editor-catalog-active > span {
    color: var(--el-color-primary);
  }
}

/* tollbar样式 */
.md-editor-toolbar-wrapper {
  .md-editor-toolbar-item {
    display: flex;
    align-items: center;
  }
}
</style>
